/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pers.sakurasora.lesson.service.impl;

import com.github.pagehelper.PageHelper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.sakurasora.lesson.dao.SysUserDao;
import pers.sakurasora.lesson.dto.UserDto;
import pers.sakurasora.lesson.entity.SysUser;
import pers.sakurasora.lesson.service.UserService;

/**
 * @author SakuraSora
 * @Email 1468071675@qq.com
 * @DateTime 2018-10-30 15:45:49
 *
 * @Description
 *              服务层(业务逻辑层)实现类--用户
 */
    
@Service /*标注它是一个Service组件;
           需要在applicationContext.xml文件中配置<context:component-scan base-package="pers.sakurasora.lesson.service.impl"/>,
           注记才会生效，才会作为一个组件注册到spring的容器中去*/
public class UserServiceImpl implements UserService{

    @Autowired//自动依赖注入--业务逻辑层要依赖于DAO层，去访问DAO层
    SysUserDao dao;
    
    @Override
    public SysUser authenticate(String account, String password) {
        //根据账号查询用户
        SysUser user = dao.selectByAccount(account);
        if (user != null && password.equals(user.getPassword())) {
            return user;
        }
        return  null;
         /*
            不提倡使用：
            user.getPassword().equals(password)
            因为：
                如果user.getPassword()为空则会出现空指针异常
        */
    }

    @Override
    public SysUser getUserById(int id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public boolean addUser(SysUser user) {
        boolean result = false;
        try {
            //可能存在异常(不希望用户在前端页面看见异常信息，需要捕捉处理异常，开发人员可在控制台服务器日志输出端查看异常)
            result = dao.insert(user) == 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    @Transactional
    public boolean deleteUser(int id) {
        return dao.deleteByPrimaryKey(id) == 1;
    }

    @Override
    @Transactional
    public boolean modifyUser(SysUser user) {
        return dao.update(user) == 1;
    }

    @Override
    public List<SysUser> getUserList(UserDto dto) {
        //从第1页开始，每页5条记录
        PageHelper.startPage(1, 5); 
        return dao.selectList();
    }

    @Override
    public boolean checkAccount(String account) {
        return dao.selectByAccount(account) == null;
    }

}
